package com.weidian.mobile.open.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.weidian.mobile.open.pojo.SaleMachine;
import com.weidian.mobile.open.repository.SaleMachineRepository;
import com.weidian.mobile.open.utils.HttpUtils;
import com.weidian.mobile.open.utils.StringUtils;

@RestController
public class MiniAppController {

	public static final Logger logger = LoggerFactory.getLogger(MiniAppController.class);
	
	@Autowired
	StringRedisTemplate jedisTemplate;
	
	@Autowired
	SaleMachineRepository saleMachineRepository;
	
	@RequestMapping(value = "/miniapp", method = RequestMethod.POST)
	public String sendTimeLine(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String url = request.getParameter("url");
		String miniid = request.getParameter("id");
		String phoneId = request.getParameter("phoneId");
		String path = request.getParameter("path");
		String title = request.getParameter("title");
		String desc = request.getParameter("desc");
		String thumb = request.getParameter("thumb");
		String nikcName = request.getParameter("nickName");
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("miniapp").append("weidian#ton")
			.append((url == null || url.isEmpty()) ? "" : url + "#ton")
			.append((miniid == null || miniid.isEmpty()) ? "" : miniid + "#ton")
			.append((path == null || path.isEmpty()) ? "" : path + "#ton")
			.append((title == null || title.isEmpty()) ? "" : title + "#ton")
			.append((desc == null || desc.isEmpty()) ? "" : desc + "#ton")
			.append((thumb == null || thumb.isEmpty()) ? "" : thumb + "#ton")
			.append((nikcName == null || nikcName.isEmpty()) ? "" : nikcName + "#ton");
		String token = jedisTemplate.opsForValue().get("esmobtoken");
		System.err.println(token);
		SaleMachine saleMachine = saleMachineRepository.findById(new Integer(phoneId));
		JSONObject jsonObject = new JSONObject();
		JSONObject jsonObject1 = new JSONObject();
		jsonObject1.put("type", "txt");
		jsonObject1.put("msg", StringUtils.encode(stringBuilder.toString()));
		jsonObject.put("target_type", "users");
		jsonObject.put("target", new String[]{StringUtils.getStrMD5(saleMachine.getMeid()).substring(0, 16)});
		jsonObject.put("msg", jsonObject1);
		String ret = HttpUtils.sendPostforEasemob("https://a1.easemob.com/1119161217115396/wonsionton/" + "messages", jsonObject.toJSONString(), "Bearer " + token);
		if (ret.contains("error")) {
			return "发送失败\n" + ret; 
		}
		return "成功";
	}
}
